package com.stylefeng.guns.modular.netcar.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONObject;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.Tools.CodeMsg;
import com.stylefeng.guns.core.common.Tools.Result;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.model.Pager;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.HttpUtil;
import com.stylefeng.guns.core.validater.Insert;
import com.stylefeng.guns.core.validater.Search;
import com.stylefeng.guns.core.validater.Update;
import com.stylefeng.guns.core.validater.Verify;
import com.stylefeng.guns.modular.netcar.model.OrderLine;
import com.stylefeng.guns.modular.netcar.service.IOrderLineService;
import com.stylefeng.guns.modular.netcar.warpper.OrderLineWarpper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 线路基本信息
 *
 * @author 张亚林
 * @Date 2018-10-26 10:20
 */
@Controller
@RequestMapping(value = {"/gunsApi/auth/orderLine"})
@Api(value = "线路基本信息操作相关api", tags = {"线路基本信息操作接口"})
@Slf4j(topic = "线路基本信息")
public class OrderLineController extends BaseController {
    @Autowired
    private IOrderLineService orderLineService;
    
    private static final String CACHE_STRATEGY = "local";
    @Value("${spring.mobileServerUrl}")
    private String mobileServerUrl;
    /**
     * 刷新系统线路缓存
     * @return
     */
    @ApiOperation(value = "刷新系统线路缓存", notes = "刷新系统线路缓存", httpMethod = "GET")
    @GetMapping(value = "/refreshCache", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result refreshCache() {
        String flg="kmcw2018@tty-backMag";
        System.out.println("刷新缓存地址："+mobileServerUrl+"gunsApi/auth/orderLine/refreshCache");
        try {
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("flg",flg);
            String result=HttpUtil.doPost(mobileServerUrl+"gunsApi/auth/orderLine/refreshCache",map,"utf-8");
            JSONObject jsonResult=JSON.parseObject(result);
            if(jsonResult.containsKey("code") ){
                if(jsonResult.getIntValue("code")==200){
                    return Result.success();
                }else{
                    return Result.error(CodeMsg.SERVER_EXCEPTION,jsonResult.getString("data"));
                }
            }else {
                return Result.error(CodeMsg.SERVER_EXCEPTION,"缓存服务器未给出正确的返回值");
            }
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 分页获取线路基本信息列表
     * @param orderLine
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "分页获取线路基本信息列表", notes = "分页获取线路基本信息列表", httpMethod = "POST")
    @PostMapping(value = "/pageList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result pageList(
        @RequestBody @Validated(value = Search.class) @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine,
        @ApiParam(name = "pageNum", value = "当前页数", required = true) @RequestParam(value = "pageNum",defaultValue = "1",required = true) Integer pageNum,
        @ApiParam(name = "pageSize", value = "每页显示条数", required = true) @RequestParam(value = "pageSize", defaultValue = "10000",required = true) Integer pageSize
        ) {
        try {
            Pager pager=new Pager();
            pager.setPageNumber(pageNum);//页码从1 开始
            pager.setPageSize(pageSize);
            pager.setObj(orderLine);
            /*String token= this.getToken();
            ShiroUser shiroUser= CacheKit.get(CACHE_STRATEGY, token);
            if(shiroUser!=null){
                Integer soId=shiroUser.getSoId();
                BeanUtil.setFieldValue(orderLine,"appliSoId",soId);
            }*/
            Map map= orderLineService.pageListOrderLine(pager,getToken());
            List<OrderLine> list = (List<OrderLine>) map.get("rows");
                List<Map<String, Object>> mList=new ArrayList<>();
            if(!list.isEmpty()){
                for (OrderLine o:list){
                    Map map1= BeanUtil.beanToMap(o);
                    mList.add(map1);
                }
                super.warpObject(new OrderLineWarpper(mList));
                BeanUtil.setFieldValue(map,"rows",mList);
            }
            return Result.success(map);
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 根据调度权限获取线路信息
     * @return
     */
    @ApiOperation(value = "根据调度权限获取线路信息", notes = "根据调度权限获取线路信息", httpMethod = "GET")
    @GetMapping(value = "/getLineInf", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getLineInf(
            @ApiParam(name = "isAll", value = "是否所有线路 0:根据调度权限,1:获取所有", required = true) @RequestParam(value = "isAll",required = true) String isAll,
            @ApiParam(name = "state", value = "线路状态", required = false) @RequestParam(value = "state",required = false) String state
    ) {
        try {
            return Result.success(orderLineService.selectListOrderLine(isAll,state,getToken()));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 获取线路基本信息列表
     * @param orderLine
     * @return
     */
    @ApiOperation(value = "获取审批线路基本信息列表", notes = "获取审批线路基本信息列表", httpMethod = "POST")
    @PostMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result list(
        @RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine) {
        try {
            List<OrderLine>  list=orderLineService.selectListOrderLine(orderLine,getToken());
            if(list!=null&&list.size()>0){
                List<Map<String, Object>> mList=new ArrayList<>();
                list.forEach(o->mList.add(BeanUtil.beanToMap(o)));
                return Result.success(super.warpObject(new OrderLineWarpper(mList)));
            }
            return Result.error(CodeMsg.NOT_FIND_DATA);
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 通过主键获取线路基本信息对象
     * @param id
     * @return
     */
    @ApiOperation(value = "通过主键获取线路基本信息对象", notes = "通过主键获取线路基本信息对象", httpMethod = "GET")
    @GetMapping(value = "/getById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result getById(@ApiParam(name = "id", value = "主键ID", required = true) @RequestParam(value = "id", required = true) String  id) {
        try {
            OrderLine orderLine=orderLineService.findOrderLineById(id,getToken());
            List<Map<String, Object>> mList=new ArrayList<>();
            Map map= BeanUtil.beanToMap(orderLine);
            mList.add(map);
            return Result.success(super.warpObject(new OrderLineWarpper(mList)));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }

    /**
     * 新增线路基本信息数据
     *
     * @param orderLine
     * @param result
     * @return
     */
    @ApiOperation(value = "新增线路基本信息数据", notes = "新增线路基本信息数据", httpMethod = "POST")
    @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "新增线路基本信息数据")
    @ResponseBody
    public Result add(@Validated(value = Insert.class) @RequestBody @ApiParam(name = "orderLine ", value = "线路基本信息对象")OrderLine orderLine ,BindingResult result
    ) {
        if (result.hasErrors()) {
            return  Result.error(BizExceptionEnum.REWUIRED_PARA_NOT_NULL);
        }
        try {
            orderLineService.insertOrderLine(orderLine,getToken());
            return Result.success("新增线路信息成功！");
        }catch(Exception e){
            String msg=e.getMessage();
            if(StringUtils.isBlank(msg)){
                msg="添加线路失败!";
            }else{
                if(msg.indexOf("for key 'index_1'")>-1){
                    msg="插入失败,所添加线路已经存在！";
                }
            }
            ErrorTip tip=new ErrorTip(500,msg);
            return Result.error(tip);
        }
    }


    /**
     * 更新线路基本信息数据
     * @param orderLine
     * @param result
     * @return
     */
    @ApiOperation(value = "更新线路基本信息数据", notes = "更新线路基本信息数据", httpMethod = "POST")
    @PostMapping(value = "/update", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "更新线路基本信息数据")
    @ResponseBody
    public Result update(@Validated(value = Update.class) @RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine, BindingResult result
    ) {
        if (result.hasErrors()) {
            return Result.error(CodeMsg.SERVER_EXCEPTION,"参数异常！");
        }
        try {
            String id=orderLine.getOlId();
            OrderLine old=this.orderLineService.selectById(id);
            if (old!=null){
                //复制旧的属性过来，忽略null属性，忽略null值，有值的以新的为主，null的则以旧为主
                BeanUtil.copyProperties(orderLine, old,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                old.updateById();
            }else{
                return Result.error(CodeMsg.NOT_FIND_DATA);
            }
          return Result.success();
        }catch(Exception e){
            String msg=e.getMessage();
            if(msg.indexOf("for key 'index_1'")>-1){
                msg="线路已经存在！";
            }
            return Result.error(CodeMsg.SERVER_EXCEPTION,msg);
        }
    }
    @ApiOperation(value = "审核线路基本信息数据", notes = "审核线路基本信息数据", httpMethod = "POST")
    @PostMapping(value = "/verify", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "线路审核")
    @ResponseBody
    public Result verify(@Validated(value = Verify.class) @RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine, BindingResult result)
    {
        if (result.hasErrors()) {
            return Result.error(CodeMsg.SERVER_EXCEPTION,"参数异常,ID和审核状态不能为空！");
        }
        String id=orderLine.getOlId();
        OrderLine old=this.orderLineService.selectById(id);
        BeanUtil.copyProperties(orderLine,old,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        old.updateById();
        return Result.success(CodeMsg.SUCCESS);
    }
    
    /**
     * 删除线路基本信息数据
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除线路基本信息数据", notes = "删除线路基本信息数据", httpMethod = "GET")
    @GetMapping(value = "/delBatch", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "删除线路基本信息数据")
    @ResponseBody
    public Result delBatch(
            @ApiParam(name = "ids", value = "主键ID字符数组", required = true) @RequestParam(value = "ids", required = true) String ids
    ) {
        try {
            orderLineService.deleteBatchOrderLine(ids.split(","),getToken());
            return Result.success();
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
	/**
     * 删除线路基本信息数据
     * @param orderLine
     * @return
     */
    @ApiOperation(value = "删除线路基本信息数据", notes = "删除线路基本信息数据", httpMethod = "POST")
    @PostMapping(value = "/del", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @BussinessLog(value = "删除线路基本信息数据")
    @ResponseBody
    public Result del(@RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine) {
        try {
            orderLineService.deleteOrderLine(orderLine,getToken());
            return Result.success();
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
    /**
     * 获取线路基本信息的Key-Value列表，用于html的Select数据源
     * @param orderLine
     * @return
     */
    @ApiOperation(value = "获取线路基本信息的Key-Value列表，用于html的Select数据源", notes = "获取线路基本信息的Key-Value列表，用于html的Select数据源", httpMethod = "POST")
    @PostMapping(value = "/optionsList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes= MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Result optionsList(@RequestBody @ApiParam(name = "orderLine", value = "线路基本信息对象")OrderLine orderLine) {
        try {
            return Result.success(orderLineService.optionsOrderLine(orderLine,getToken()));
        }catch(Exception e){
            return Result.error(CodeMsg.SERVER_EXCEPTION,e.getMessage());
        }
    }
	private String getToken(){
		return getHttpServletRequest().getHeader("Authorization").substring(7);
    }
}
